const express = require("express");
const boom = require("boom");
const userRouter = require("./user");
const arrangeRouter = require("./arrange");
const adminUserRouter = require("./admin_user");
const adminArticleRouter = require("./admin_article");


//客户端
const memberUserRouter = require("./memberUser");//用户表
const homeRouter = require("./home");//客户端首页接口
const articleRouter = require("../web_router/article");//帖子接口
const communityRouter = require("../web_router/community");//分类接口


const toolRouter = require("./tool");//工具

const jwtAuth = require("./jwt");//验证token
const Result = require('../models/Result')

//注册路由
const router = express.Router();

router.use(jwtAuth)

router.get('/',function(req,res){
    res.send("欢迎后台");
})
//后台
router.use('/adminUser',adminUserRouter)
router.use('/user',userRouter)
router.use('/arrange',arrangeRouter)
router.use('/tool',toolRouter)
router.use('/adminArticle',adminArticleRouter)


//客户端
router.use('/memberUser',memberUserRouter)
router.use('/home',homeRouter)
router.use('/article',articleRouter)
router.use('/community',communityRouter)



/*
*集中处理404请求的中间件
*注意:该中间件必须放在正常处理流程之后
*否则,会拦截正常请求
*/
router.use(function(req,res,next){
    next(boom.notFound("接口不存在"));
})

/*
*自定义路由异常处理中间件
*注意两点:
*第一，方法的参数不能减少
*第二，方法的必须放在路由最后
*/

router.use((err,req,res,next)=>{
    console.log(err)
    if(err.code && err.code =='credentials_required' ){
        const { status=401,message } = err
        new Result(null,'token失效',{
            error:status,
            errorMsg:message
        }).jwtError(res.status(status))
        
    }else if(err.code && err.code =='invalid_token' ){
        const { status=401,message } = err
        new Result(null,'token过期,请重新登录',{
            error:status,
            errorMsg:message
        }).jwtError(res.status(status))
        
    }else{
        const msg = (err && err.message) || '系统错误'
        const statusCode = (err.output && err.output.statusCode) || 500
        const errorMsg = (err.output && err.output.payload && err.output.payload.error) || err.message
        new Result(null,msg,{
            error:statusCode,
            errorMsg
        }).fail(res.status(statusCode))
    }
    
})





module.exports = router